﻿using NLog;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using WTAppletProjectHTTPS.Models;

namespace WTAppletProjectHTTPS.Controllers
{
   
    public class ColaPackingFinalInspectionQueryController : ApiController
    {
        private static readonly Logger Logger = NLog.LogManager.GetCurrentClassLogger();

        // POST api/<controller>
        public async Task<HttpResponseMessage> Post([FromBody] ColaPackingFinalInspectionQuery CPFICQ)
        {
            ReturnObjectQuery RO = new ReturnObjectQuery();
            if (CPFICQ.PageNumber <= 0 || CPFICQ.PageSize <= 0)
            {
                Logger.Warn("分页参数无效");
                RO.Status = HttpStatusCode.BadRequest;
                RO.Message = "分页参数无效";
                RO.Data = null;
                Logger.Error("分页参数无效");
                return Request.CreateResponse(HttpStatusCode.BadRequest, RO);
            }

            try
            {
                using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString))
                {
                    await connection.OpenAsync();

                    var whereClause = "WHERE 1=1";
                    if (CPFICQ.CPFIC_ID != 0)
                    {
                        whereClause += " AND CPFIID = @ID";
                    }
                    if (CPFICQ.CPFIC_Time != default(DateTime))
                    {
                        whereClause += " AND CPFITime = @Time";
                    }
                    if (!string.IsNullOrEmpty(CPFICQ.CPFIC_Name))
                    {
                        whereClause += " AND CPFIName LIKE @Name";
                    }
                    if (!string.IsNullOrEmpty(CPFICQ.CPFIC_ProductModel))
                    {
                        whereClause += " AND CPFIProductModel LIKE @ProductModel";
                    }
                    if (!string.IsNullOrEmpty(CPFICQ.CPFIC_OrderNumber))
                    {
                        whereClause += " AND CPFIOrderNumber LIKE @OrderNumber";
                    }
                    if (!string.IsNullOrEmpty(CPFICQ.CPFIC_LineBody))
                    {
                        whereClause += " AND CPFILineBody LIKE @LineBody";
                    }
                    if (CPFICQ.CPFIC_TotalInspectionQuantity > 0)
                    {
                        whereClause += " AND CPFITotalInspectionQuantity = @TotalInspectionQuantity";
                    }
                    if (CPFICQ.CPFIC_DefectiveQuantity > 0)
                    {
                        whereClause += " AND CPFIDefectiveQuantity = @DefectiveQuantity";
                    }
                    if (!string.IsNullOrEmpty(CPFICQ.CPFIC_DefectiveReasonAndQuantity))
                    {
                        whereClause += " AND CPFIDefectiveReasonAndQuantity LIKE @DefectiveReasonAndQuantity";
                    }

                    var query = $@"
                        SELECT 
                            CPFIID, CPFIName, CPFITime, CPFIProductModel, CPFIOrderNumber, 
                            CPFILineBody, CPFITotalInspectionQuantity, CPFIDefectiveQuantity, CPFIDefectiveReasonAndQuantity,CPFICreateCreator,CPFICreateTime,
                            COUNT(*) OVER() AS TotalCount
                        FROM 
                            (SELECT 
                                CPFIID, CPFIName, CPFITime, CPFIProductModel, CPFIOrderNumber, 
                                CPFILineBody, CPFITotalInspectionQuantity, CPFIDefectiveQuantity, CPFIDefectiveReasonAndQuantity,CPFICreateCreator,CPFICreateTime,
                                ROW_NUMBER() OVER(ORDER BY CPFIID) AS RowNum
                             FROM ColaPackingFinalInspection {whereClause}) AS Result
                        WHERE 
                            RowNum BETWEEN @StartRow AND @EndRow
                        ORDER BY RowNum";

                    int startRow = (CPFICQ.PageNumber - 1) * CPFICQ.PageSize + 1;
                    int endRow = CPFICQ.PageNumber * CPFICQ.PageSize;

                    var parameters = new List<SqlParameter>
                    {
                        new SqlParameter("@StartRow", SqlDbType.Int) { Value = startRow },
                        new SqlParameter("@EndRow", SqlDbType.Int) { Value = endRow }
                    };
                    if (CPFICQ.CPFIC_ID != 0)
                    {
                        parameters.Add(new SqlParameter("@ID", SqlDbType.Int) { Value = CPFICQ.CPFIC_ID });
                    }
                    if (CPFICQ.CPFIC_Time != default(DateTime))
                    {
                        parameters.Add(new SqlParameter("@Time", SqlDbType.DateTime) { Value = CPFICQ.CPFIC_Time });
                    }
                    if (!string.IsNullOrEmpty(CPFICQ.CPFIC_Name))
                    {
                        parameters.Add(new SqlParameter("@Name", SqlDbType.NVarChar, 50) { Value = $"%{CPFICQ.CPFIC_Name}%" });
                    }
                    if (!string.IsNullOrEmpty(CPFICQ.CPFIC_ProductModel))
                    {
                        parameters.Add(new SqlParameter("@ProductModel", SqlDbType.NVarChar, 50) { Value = $"%{CPFICQ.CPFIC_ProductModel}%" });
                    }
                    if (!string.IsNullOrEmpty(CPFICQ.CPFIC_OrderNumber))
                    {
                        parameters.Add(new SqlParameter("@OrderNumber", SqlDbType.NVarChar, 50) { Value = $"%{CPFICQ.CPFIC_OrderNumber}%" });
                    }
                    if (!string.IsNullOrEmpty(CPFICQ.CPFIC_LineBody))
                    {
                        parameters.Add(new SqlParameter("@LineBody", SqlDbType.NVarChar, 50) { Value = $"%{CPFICQ.CPFIC_LineBody}%" });
                    }
                    if (CPFICQ.CPFIC_TotalInspectionQuantity > 0)
                    {
                        parameters.Add(new SqlParameter("@TotalInspectionQuantity", SqlDbType.Int) { Value = CPFICQ.CPFIC_TotalInspectionQuantity });
                    }
                    if (CPFICQ.CPFIC_DefectiveQuantity > 0)
                    {
                        parameters.Add(new SqlParameter("@DefectiveQuantity", SqlDbType.Int) { Value = CPFICQ.CPFIC_DefectiveQuantity });
                    }
                    if (!string.IsNullOrEmpty(CPFICQ.CPFIC_DefectiveReasonAndQuantity))
                    {
                        parameters.Add(new SqlParameter("@DefectiveReasonAndQuantity", SqlDbType.NVarChar, 500) { Value = $"%{CPFICQ.CPFIC_DefectiveReasonAndQuantity}%" });
                    }

                    using (var command = new SqlCommand(query, connection))
                    {
                        command.Parameters.AddRange(parameters.ToArray());
                        using (var reader = await command.ExecuteReaderAsync())
                        {
                            if (!reader.HasRows)
                            {
                                Logger.Warn("未找到记录");
                                RO.Status = HttpStatusCode.NotFound;
                                RO.Message = "未找到记录";
                                RO.Data = null;
                                return Request.CreateResponse(HttpStatusCode.NotFound, RO);
                            }

                            var records = new List<ColaPackingFinalInspection>();
                            int totalCount = 0;
                            while (await reader.ReadAsync())
                            {
                                if (totalCount == 0)
                                {
                                    totalCount = reader.GetInt32(reader.GetOrdinal("TotalCount"));
                                }

                                records.Add(new ColaPackingFinalInspection
                                {
                                    CPFIC_ID = reader.GetInt32(reader.GetOrdinal("CPFIID")),
                                    CPFIC_Name = reader.GetString(reader.GetOrdinal("CPFIName")),
                                    CPFIC_Time = reader.GetDateTime(reader.GetOrdinal("CPFITime")),
                                    CPFIC_ProductModel = reader.GetString(reader.GetOrdinal("CPFIProductModel")),
                                    CPFIC_OrderNumber = reader.GetString(reader.GetOrdinal("CPFIOrderNumber")),
                                    CPFIC_LineBody = reader.GetString(reader.GetOrdinal("CPFILineBody")),
                                    CPFIC_TotalInspectionQuantity = reader.GetInt32(reader.GetOrdinal("CPFITotalInspectionQuantity")),
                                    CPFIC_DefectiveQuantity = reader.GetInt32(reader.GetOrdinal("CPFIDefectiveQuantity")),
                                    CPFIC_DefectiveReasonAndQuantity = reader.GetString(reader.GetOrdinal("CPFIDefectiveReasonAndQuantity")),
                                    CPFI_CreateCreator = reader.GetString(reader.GetOrdinal("CPFICreateCreator")),
                                    CPFI_CreateTime = reader.GetDateTime(reader.GetOrdinal("CPFICreateTime")),
                                });
                            }

                            Logger.Info("查询成功");
                            RO.Status = HttpStatusCode.OK;
                            RO.Message = "OK";
                            RO.Data = records;
                            RO.TotalCount = totalCount;
                            RO.PageNumber = CPFICQ.PageNumber;
                            RO.PageSize = CPFICQ.PageSize;
                            return Request.CreateResponse(HttpStatusCode.OK, RO);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("查询失败: " + ex.Message);
                RO.Status = HttpStatusCode.InternalServerError;
                RO.Message = "Error: " + ex.Message;
                RO.Data = null;
                return Request.CreateResponse(HttpStatusCode.InternalServerError, RO);
            }
        }
    }
}
